package com.xvwang.blog.servlet;

import com.xvwang.blog.dao.UserDao;
import com.xvwang.blog.model.User;
import com.xvwang.blog.service.UserService;
import org.mindrot.jbcrypt.BCrypt;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/do-login")
public class DoLoginServlet extends HttpServlet {
    private final UserService userService = new UserService();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //读取用户提交的信息
        req.setCharacterEncoding("utf-8");

        String username = req.getParameter("username");

        String password = req.getParameter("password");

        User user = userService.login(username,password);
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html");
        PrintWriter writer = resp.getWriter();

        //1登录成功，user！= null
        //2登陆失败，由于用户名注册导致的失败 user == null
        //3由于用户操作系统导致的失败    以异常方式体现
        if(user!=null){
                //登录成功
                HttpSession session = req.getSession();
                session.setAttribute("currentUser",user);
                writer.printf("<p>登录成功，点击<a href='/'>此处</a>跳转到首页</p>\r\n");
                return;
        }
            writer.printf("<p>登陆失败，点击<a href='/login.html'>此处</a>重新登录</p>\r\n");
    }
}
